package com.itheima.web.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.util.JwtUtil;
import com.itheima.util.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.temporal.Temporal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    // 发送短信
    @GetMapping("/sendSms")
    public String sendSms(String telephone, HttpSession session) {
        // 生成6位随机验证码
        String smsCode = RandomUtil.randomNumbers(6);
        // 向session中存储验证码
        // session.setAttribute("sms_" + telephone, smsCode);

        // 向redis中存储（5分钟有效期）
        redisTemplate.opsForValue().set("sms_" + telephone, smsCode ,5,TimeUnit.MINUTES);

        // 调用smsUtil工具类发送短信
        // SmsUtil.sendSms(telephone, smsCode);
        System.err.println("发送验证码：" + smsCode);
        return "ok";
    }

    @Autowired
    private UserService userService;

    // 用户登录
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> params, HttpSession session) {
        // 声明返回结果
        Map<String, Object> loginResult = new HashMap<>();

        // 1.接收参数
        String telephone = params.get("telephone");
        String smsCode = params.get("smsCode");
        // 2.从session中获取验证码
       //  String codeFromSession = (String) session.getAttribute("sms_" + telephone);
        // 2. 从redis中获取
        String codeFromRedis = (String) redisTemplate.opsForValue().get("sms_" + telephone);
        // 3.判断验证码
        if ((codeFromRedis == null && smsCode == null) || (!smsCode.equals(codeFromRedis))) {
            loginResult.put("code", 0);
            return loginResult;
        }

        // 清除验证码
        // session.removeAttribute("sms_" + telephone);
        redisTemplate.delete("sms_" + telephone);

        // 4.根据手机号查询
        User user = userService.findByTelephone(telephone);
        if (user == null) {
            loginResult.put("code", 0);
            return loginResult;
        }

        // 5.登录成功了...
        // 将user转为map
        user.setPassword(null);
        Map<String, Object> claims = BeanUtil.beanToMap(user);
        // 通过jwt制作令牌
        String token = JwtUtil.createToken(claims);
        loginResult.put("code", 1);
        loginResult.put("token", token);
        return loginResult;
    }

    @GetMapping("/verify")
    public String verify(@RequestHeader("Authorization") String token){

        try {
            Map map = JwtUtil.parseToken(token);
            System.out.println(map);
        } catch (Exception e) {
            e.printStackTrace();
            return "401"; // 权限不足
        }

        return "ok"; // 登录成功
    }
}
